package com.qujia.station.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qujia.common.annotation.Log;
import com.qujia.common.constant.Constants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.Station;
import com.qujia.station.domain.StationDeviceManage;
import com.qujia.station.domain.dto.StationDeviceManageDTO;
import com.qujia.station.domain.vo.EnterpriseAndStationVo;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IStationDeviceManageService;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.StationDeviceAudioService;
import com.qujia.station.utils.Methods;
import com.qujia.system.domain.SysStationUser;
import com.qujia.system.service.ISysStationUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 油站设备管理Controller
 *
 * @author qujia
 * @date 2021-01-13
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/station/manage")
@Api(tags = "StationDeviceManageController", description = "设备管理")
public class StationDeviceManageController extends BaseController {
    @Autowired
    private IStationDeviceManageService stationDeviceManageService;
    @Autowired
    private ISysStationUserService stationUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IStationService stationService;

    @Resource
    private StationDeviceAudioService stationDeviceAudioService;

    /**
     * 查询油站设备管理列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "设备列表", notes = "示例：https://yftx-test.xailife.com/prod-api/station/manage/list?pageNum=1&pageSize=10&deviceSerialNum=123&likeDeviceNo=123")
    public TableDataInfo list(StationDeviceManage stationDeviceManage) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        if ("1".equals(currentUser.getUser().getUserLevel())) {
            List<String> sta = new ArrayList<>();
            SysStationUser stationUser = new SysStationUser();
            stationUser.setEnterpriseId(currentUser.getUser().getEnterpriseId());
            List<SysStationUser> stationUsers = stationUserService.selectSysStationUserList(stationUser);
            for (SysStationUser sysStationUser : stationUsers) {
                sta.add(sysStationUser.getStationId() + "");
            }
            if (stationUsers != null && stationUsers.size() > 0) {
                stationDeviceManage.setStationIdList(sta);
            } else {
                stationDeviceManage.setStationId(0L);
            }
        } else if ("2".equals(currentUser.getUser().getUserLevel())) {
            stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        }
        if (SecurityUtils.isPartner()) {
            EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
            stationDeviceManage.setStationIdList(itemIds.getStationIdsStr());
        }
        /*SysDept dept =new SysDept();
        dept.setDeptId(currentUser.getUser().getStationId());
        List<String> list = deptService.selectDeptId(dept);
        if(list!=null && list.size()>0){
            stationDeviceManage.setStationIdList(list);
            stationDeviceManage.setStationId(null);
        }*/

        startPage();
        List<StationDeviceManage> manageList = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
        for (StationDeviceManage stationDeviceManage1 : manageList) {
            if (stationDeviceManage1.getUserIds() != null && !"".equals(stationDeviceManage1.getUserIds())) {
                stationDeviceManage1.setUserIdList(Arrays.asList(stationDeviceManage1.getUserIds().split(",")));
            } else {
                stationDeviceManage1.setUserIdList(new ArrayList<>());
            }

            if ("3".equals(stationDeviceManage1.getDeviceType()) && "1".equals(stationDeviceManage1.getDeviceFactory())) {

                Object acceccTokenObj = redisCache.getCacheObject(Constants.DEVICE_CLIENT_TOKEN + stationDeviceManage1.getClientId());
                String token = "";
                if (Objects.isNull(acceccTokenObj)) {
                    Methods m = Methods.getInstance();
                    m.init(stationDeviceManage1.getClientId(), stationDeviceManage1.getClientSecret());
                    String freedomToken = m.getFreedomToken();
//                    JSONObject json = new JSONObject(freedomToken);
//
//                    JSONObject body = json.getJSONObject("body");
//                    token = body.getString("access_token");
                    redisCache.setCacheObject(Constants.DEVICE_CLIENT_TOKEN + stationDeviceManage1.getClientId(), freedomToken, 30, TimeUnit.DAYS);

                } else {
                    token = acceccTokenObj.toString();
                }
                stationDeviceManage1.setAccessToken(token);
            }
        }
        return getDataTable(manageList);
    }

    /**
     * 查询油站设备管理列表
     */
    @GetMapping("/feieList")
    public TableDataInfo feieList(StationDeviceManage stationDeviceManage) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        if ("1".equals(currentUser.getUser().getUserLevel())) {
            List<String> sta = new ArrayList<>();
            SysStationUser stationUser = new SysStationUser();
            stationUser.setEnterpriseId(currentUser.getUser().getEnterpriseId());
            List<SysStationUser> stationUsers = stationUserService.selectSysStationUserList(stationUser);
            for (SysStationUser sysStationUser : stationUsers) {
                sta.add(sysStationUser.getStationId() + "");
            }
            if (stationUsers != null && stationUsers.size() > 0) {
                stationDeviceManage.setStationIdList(sta);
            } else {
                stationDeviceManage.setStationId(0L);
            }
        } else if ("2".equals(currentUser.getUser().getUserLevel())) {
            stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        } else if ("7".equals(currentUser.getUser().getUserLevel())) {
            List<Enterprise> enterpriseList =
                    enterpriseService.list(new QueryWrapper<Enterprise>().in("author_id", currentUser.getUser().getUserId()));
            if (enterpriseList != null && enterpriseList.size() > 0) {
                List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                List<Station> stationList =
                        stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds));
                List<Long> stationIds = stationList.stream().map(Station::getStationId).collect(Collectors.toList());
                stationDeviceManage.setStationIds(stationIds);
            } else {
                throw new CustomException("未创建油企");
            }
        }
        /*SysDept dept =new SysDept();
        dept.setDeptId(currentUser.getUser().getStationId());
        List<String> list = deptService.selectDeptId(dept);
        if(list!=null && list.size()>0){
            stationDeviceManage.setStationIdList(list);
            stationDeviceManage.setStationId(null);
        }*/
        stationDeviceManage.setDeviceType("3");
        startPage();
        List<StationDeviceManage> manageList = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
        for (StationDeviceManage stationDeviceManage1 : manageList) {
            if (stationDeviceManage1.getUserIds() != null && !"".equals(stationDeviceManage1.getUserIds())) {
                stationDeviceManage1.setUserIdList(Arrays.asList(stationDeviceManage1.getUserIds().split(",")));
            } else {
                stationDeviceManage1.setUserIdList(new ArrayList<>());
            }
        }
        return getDataTable(manageList);
    }

    /**
     * 导出油站设备管理列表
     */
    @Log(title = "油站设备管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(StationDeviceManage stationDeviceManage) {

        LoginUser currentUser = SecurityUtils.getLoginUser();

        /*SysDept dept =new SysDept();
        dept.setDeptId(currentUser.getUser().getDeptId());
        List<String> list = deptService.selectDeptId(dept);
        if(list!=null && list.size()>0){
            stationDeviceManage.setStationIdList(list);
            stationDeviceManage.setStationId(null);
        }*/
        stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        List<StationDeviceManage> manageList = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
        ExcelUtil<StationDeviceManage> util = new ExcelUtil<StationDeviceManage>(StationDeviceManage.class);
        return util.exportExcel(manageList, "manage");
    }

    /**
     * 获取油站设备管理详细信息
     */
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return AjaxResult.success(stationDeviceManageService.selectStationDeviceManageById(deviceId));
    }

    /**
     * 新增油站设备管理
     */
    @Log(title = "油站设备管理", businessType = BusinessType.INSERT)
    @ApiOperation("新增设备")
    @PostMapping
    public AjaxResult add(@RequestBody @Valid StationDeviceManage stationDeviceManage) throws Exception {
//        LoginUser currentUser = SecurityUtils.getLoginUser();
//        if(!"2".equals(currentUser.getUser().getUserLevel())){
//            return AjaxResult.error("非站点不可使用设备管理");
//        }
        //stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        //stationDeviceManage.setStationName(currentUser.getUser().getDept().getDeptName());
        if (stationDeviceManage.getStationId() == null) {
            return AjaxResult.error("油站信息错误");
        }
        if (stationDeviceManage.getUserIdList() != null && stationDeviceManage.getUserIdList().size() > 0) {
            stationDeviceManage.setUserIds(String.join(",", stationDeviceManage.getUserIdList()));
        }
        if (stationDeviceManage.getGunNoList() != null && stationDeviceManage.getGunNoList().size() > 0) {
            stationDeviceManage.setGunNo(String.join(",", stationDeviceManage.getGunNoList()));
        }
        //云喇叭
        if ("4".equals(stationDeviceManage.getDeviceType())) {
            stationDeviceManage.setDeviceFactory("4");
        }
        // 新款K4
        if ("3".equals(stationDeviceManage.getDeviceFactory())) {
            stationDeviceManage.setDeviceType("3");
        }
        return toAjax(stationDeviceManageService.insertStationDeviceManage(stationDeviceManage));
    }

    /**
     * 新增继电器设备
     */
    @Log(title = "油站继电器设备管理", businessType = BusinessType.INSERT)
    @ApiOperation("新增继电器设备")
    @PostMapping("/addEquipment")
    public AjaxResult addEquipment(@RequestBody @Valid StationDeviceManageDTO stationDeviceManageDTO) {
        return toAjax(stationDeviceManageService.insertStationDeviceManage(stationDeviceManageDTO));
    }

    @GetMapping("/setVoice")
    public void setVoice(@RequestBody StationDeviceManage stationDeviceManage) throws InterruptedException {
        Methods m = Methods.getInstance();
        m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
        stationDeviceAudioService.setVoice(stationDeviceManage, m);
    }

    @GetMapping("/getK4Status")
    public AjaxResult getK4Status(@RequestBody StationDeviceManage stationDeviceManage) {
        Methods m = Methods.getInstance();
        m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
        stationDeviceManageService.checkStatus(stationDeviceManage, m);
        return null;
    }

    /**
     * 修改油站设备管理
     */
    @Log(title = "油站设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改设备")
    public AjaxResult edit(@RequestBody StationDeviceManage stationDeviceManage) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        if (stationDeviceManage.getUserIdList() != null && stationDeviceManage.getUserIdList().size() > 0) {
            stationDeviceManage.setUserIds(String.join(",", stationDeviceManage.getUserIdList()));
        }
        if (stationDeviceManage.getUserIdList() != null && stationDeviceManage.getUserIdList().size() > 0) {
            stationDeviceManage.setUserIds(String.join(",", stationDeviceManage.getUserIdList()));
        }
        //stationDeviceManage.setStationName(currentUser.getUser().getDept().getDeptName());
        return toAjax(stationDeviceManageService.updateStationDeviceManage(stationDeviceManage));
    }

    /**
     * 修改油站设备管理
     */
    @Log(title = "油站继电器设备管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editEquipment")
    @ApiOperation("修改继电器设备")
    public AjaxResult editEquipment(@RequestBody @Valid StationDeviceManageDTO stationDeviceManageDTO) {
        return toAjax(stationDeviceManageService.updateStationDeviceManage(stationDeviceManageDTO));
    }

    /**
     * 删除油站设备管理
     */
    @Log(title = "油站设备管理")
    @PostMapping("/delete")
    @ApiOperation("删除设备")
    public AjaxResult remove(@RequestBody List<Long> deviceIds) {
        Long[] longs = deviceIds.stream().toArray(Long[]::new);
        return toAjax(stationDeviceManageService.deleteStationDeviceManageByIds(longs));
    }

    /**
     * 状态修改
     */
    @Log(title = "油站设备管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeManageStatus")
    public AjaxResult changeManageStatus(@RequestBody StationDeviceManage stationDeviceManage) {
        return toAjax(stationDeviceManageService.updateStationDeviceManage(stationDeviceManage));
    }
}
